package com.gorio.lms.controller;

import com.gorio.lms.entities.Admin;
import com.gorio.lms.mapper.BookEntityMapper;
import com.gorio.lms.mapper.BookInfoMapper;
import com.gorio.lms.tools.MyLoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;


/**
 * Project Name spring-boot-01-helloworld
 * Package Name com.gorio.xdce.controller
 * Class Name LoginController
 * Created by Gorio
 *
 * @author Gorio
 * @date 2020/9/13 16:13
 */

@Controller
public class LoginController {

    private static final Logger log = MyLoggerFactory.getLogger(LoginController.class);

    @Autowired
    BookInfoMapper bookInfoMapper;

    @Autowired
    BookEntityMapper bookEntityMapper;

    @PostMapping(value = "/user/login")
    public String login(@RequestParam("username") String userName,
                        @RequestParam("password") String password,
                        @RequestParam("timestamps") String time,
                        Map<String, Object> map,
                        HttpSession session,
                        HttpServletRequest request,
                        Model model) {
        String ip = request.getRemoteAddr();
        String host = request.getRemoteHost();
        int port = request.getRemotePort();
        log.info("recv username is {}, password is {}, time is {}", userName, password, time);
        if (StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(password)) {
            //两个都不是空的
            if (Admin.getInstance().authentication(userName, password, time)) {
                session.setAttribute("loginUser", userName);
                log.info("{}在{},{}@{}:{} 认证成功！", userName, new Date().toString(), host, ip, port);


                return "redirect:/main";
            }
        }
        log.info("{}在{},{}@{}:{} 认证失败了！", userName, new Date().toString(), host, ip, port);
        map.put("msg", "用户名或密码错误");
        return "login";
    }

    @GetMapping(value = "/user/signout")
    @PostMapping(value = "/user/signout")
    public String signOut(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        session.invalidate();
        //@Fixme
        return "redirect:/index";
    }


    //TODO xiawei
    @GetMapping("/main")
    @PostMapping("/main")
    public String mainPage(Model model) {
        int bookNum = bookEntityMapper.getBookCount();
        return "dashboard";
    }
}
